package com.swotxu.screwweb.common.to;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.swotxu.screwweb.common.constant.HttpConstant;
import com.swotxu.screwweb.common.exception.BizCodeEnum;

import java.util.HashMap;
import java.util.Map;

public class R extends HashMap<String, Object> {
    private static final long serialVersionUID = 1L;

    public R() {
        put(HttpConstant.HTTP_DATA_KEY_CODE, HttpConstant.HTTP_STATUS_OK);
        put(HttpConstant.HTTP_DATA_KEY_MSG, HttpConstant.MSG_SUCCESS);
    }

    public static R error() {
        return error(HttpConstant.HTTP_STATUS_SC_INTERNAL_SERVER_ERROR, "未知异常，请联系管理员");
    }

    public static R error(String msg) {
        return error(HttpConstant.HTTP_STATUS_SC_INTERNAL_SERVER_ERROR, msg);
    }

    public static R error(BizCodeEnum bizCodeEnum) {
        return error(bizCodeEnum.getCode(), bizCodeEnum.getMessage());
    }
    public static R error(int code, String msg) {
        R r = new R();
        r.put(HttpConstant.HTTP_DATA_KEY_CODE, code);
        r.put(HttpConstant.HTTP_DATA_KEY_MSG, msg);
        return r;
    }

    public static R ok(String msg) {
        R r = new R();
        r.put(HttpConstant.HTTP_DATA_KEY_MSG, msg);
        return r;
    }

    public static R ok(Map<String, Object> map) {
        R r = new R();
        r.putAll(map);
        return r;
    }

    public static R ok() {
        return new R();
    }

    public R put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    public int getCode() {
        return (int) this.get(HttpConstant.HTTP_DATA_KEY_CODE);
    }

    public boolean isOk() {
        return getCode() == 0;
    }

    public String getMessage() {
        return (String) this.get(HttpConstant.HTTP_DATA_KEY_MSG);
    }

    //利用fastjson进行逆转
    public <T> T getData() {
        return getData(HttpConstant.HTTP_DATA_KEY_DATA, new TypeReference<T>() {});
    }
    public <T> T getData(TypeReference<T> typeReference) {
        return getData(HttpConstant.HTTP_DATA_KEY_DATA, typeReference);
    }
    public <T> T getData(String key) {
        return getData(key, new TypeReference<T>() {});
    }
    //利用fastjson进行逆转
    public <T> T getData(String key, TypeReference<T> typeReference) {
        Object data = get(key);//默认是map
        String s = JSON.toJSONString(data);
        T t = JSON.parseObject(s, typeReference);
        return t;
    }

    public R setData(Object data){
        put(HttpConstant.HTTP_DATA_KEY_DATA,data);
        return this;
    }
}